import json
import os,time
from typing import Optional

from dotenv import load_dotenv
from fastapi import APIRouter, Body, Depends, UploadFile,File
from pydantic import BaseModel

from ..models.ai_models.voice_api  import run_coze_workflow as create_voice_ai

from ..crud.voice_crud import (create_voice as create_voice_db)
                       #      update_voice as  update_voice_db)
from ..crud.user_crud import get_user_by_name
from sqlalchemy.orm import Session
from ..database.db import get_db
from ..utils.jwt_handler import get_username

from ..utils.voice_tools import download_video

from ..redisbase.redis_test import user_info_init
from ..redisbase.redis_operations import check_key_exists,get_key,set_key,get_hash_field,set_hash_data,get_hash_data
import datetime

voice_routers=APIRouter(prefix="/voice", tags=["音频"])

load_dotenv()
API_TOKEN=os.getenv("API_TOKEN")
SOURCES_PATH=os.getenv("SOURCES_PATH")

@voice_routers.get("/")
async def hello_voice():
    return {
        "code":200,
        "message":"hello voice"
    }
class CreateVoiceParams(BaseModel):
    name: str = ...
    text: str = ...
@voice_routers.post("/create-vocie")
async def create_voice(
    params: CreateVoiceParams=...,
    db: Session = Depends(get_db),
    username=Depends(get_username)
):

    """
    # 创建音频
    - name 音频名称
    - text 音频描述
    """

    user = get_user_by_name(db, username).as_dict()
    user_id = user["id"]
    username = user["username"]
    current_date = time.strftime("%Y-%m-%d", time.localtime())
    user_info_init(user_id, username, current_date)
    new_video_quantity = int(get_hash_field(user_id, "ppt_quantity")) + 1
    user_info = get_hash_data(user_id)
    user_info["ppt_quantity"] = str(new_video_quantity)
    set_hash_data(user_id, user_info)

    text=params.text
    name=params.name
    username = get_user_by_name(db,username)
    WORKFLOW_ID = "7516524156826746915"
    voice_url = json.loads(create_voice_ai(text, WORKFLOW_ID, API_TOKEN)).get("output")
    voice_hou_url="sources/voices/"+f"{name}.mp3"

    voice_all_name=f"{params.name}.mp3"
    save_path = os.path.join(SOURCES_PATH, voice_hou_url)
    download_video(video_url=voice_url, save_path=save_path)

    voice_item = create_voice_db(db, voice_all_name, voice_hou_url,1)



    return {
        "code":200,
        "message": "Voice created",
        "data":{
            "voice_item":voice_item,
            "voice_url":voice_url
        }
    }

class UpdateVoiceParams(BaseModel):
    voice_id:int=...
    name:str=...


# @voice_routers.post("/update")
# async def update_voice(
#     params: UpdateVoiceParams,
#     db: Session = Depends(get_db),
#     username=Depends(get_username)
# ):
#     voice_id=params.voice_id
#     name=params.name
#     all_name=f"{name}.mp3"
#     voice_item=update_voice_db(db, voice_id=voice_id,name=all_name)
#     return {
#         "code":200,
#         "message": "Voice updated",
#         "data":{
#             "voice_item":voice_item
#         }
#     }

class VoiceUploadParams(BaseModel):
    description: Optional[str] = None
@voice_routers.post("/upload")
async def upload_voice(
    file: UploadFile = File(..., description="上传的音频文件"),
    params: VoiceUploadParams = Body(...),
    db: Session = Depends(get_db),
    username: str = Depends(get_username)
):
    """
    上传音频文件接口
    - file: 音频文件（支持 .mp3/.wav/.ogg）
    - description: 可选描述
    """
    # 检查文件类型是否合法
    allowed_types = ["audio/mpeg", "audio/wav", "audio/ogg"]
    if file.content_type not in allowed_types:
        return {
            "code": 400,
            "message": "不支持的音频格式",
            "data": None
        }

    # 获取文件扩展名
    file_extension = os.path.splitext(file.filename)[1].lower()
    if file_extension not in [".mp3", ".wav", ".ogg"]:
        return {
            "code": 400,
            "message": "不支持的音频格式",
            "data": None
        }

    # 加载环境变量中的存储路径
    load_dotenv()
    SOURCES_PATH = os.getenv("SOURCES_PATH")

    # 构建音频保存路径
    save_dir = os.path.join(SOURCES_PATH, "sources", "voices","download")
    os.makedirs(save_dir, exist_ok=True)  # 自动创建目录

    # 使用时间戳生成唯一文件名
    timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
    new_filename = f"{timestamp}_{file.filename}"
    save_path = os.path.join(save_dir, new_filename)

    # 保存文件到本地
    with open(save_path, "wb") as buffer:
        content = await file.read()
        buffer.write(content)

    # 构造数据库记录的相对路径
    relative_path = os.path.join("sources", "voices", new_filename)

    # 写入数据库
    voice_item = create_voice_db(db, name=new_filename, path=relative_path)

    return {
        "code": 200,
        "message": "音频上传成功",
        "data": {
            "voice_item": voice_item,
            "file_name": new_filename,
            "file_path": relative_path,
            "description": params.description
        }
    }